﻿using HZY.Framework.DependencyInjection;
using MiniExcelLibs;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Long.SpraySCADA
{
    public partial class PageLogManage : UIPage, ISingletonSelfDependency
    {
        public PageLogManage()
        {
            InitializeComponent();
            IniLogData();
            this.txt_ShowLog.ShowScrollBar = true;
        }

        private void IniLogData()
        {
            string logPath = Path.Combine(Application.StartupPath, "Logs");
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            //获取该地址下的所有子目录
            string[] dirNames = Directory.GetDirectories(logPath);
            dirNames.ForEach(dirName =>
            {
                this.cb_Date.Items.Add(Path.GetFileName(dirName));
            });
        }

        private void cb_Date_SelectedIndexChanged(object sender, EventArgs e)
        {
            //选择日期后，遍历all文件等级
            string logGrade = Path.Combine(Application.StartupPath, "Logs", this.cb_Date.SelectedItem.ToString());

            string[] dirNames = Directory.GetDirectories(logGrade);
            this.cb_LogLev.Items.Clear();
            dirNames.ForEach(dirName =>
            {
                this.cb_LogLev.Items.Add(Path.GetFileName(dirName));
            });
        }

        private void cb_LogLev_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cb_Date.SelectedItem == null)
            {
                UIMessageTip.ShowError("请选择日期！");
                return;
            }
            if (this.cb_LogLev.SelectedItem == null)
            {
                UIMessageTip.ShowError("请选择日志等级！");
                return;
            }
            //选择等级后，遍历all log
            string logTxt = Path.Combine(Application.StartupPath, "Logs", this.cb_Date.SelectedItem.ToString(), this.cb_LogLev.SelectedItem.ToString());
            //获取文件夹名
            //string[] dirNames = Directory.GetDirectories(logTxt);
            this.lb_Files.Items.Clear();
            string[] fileNames = Directory.GetFiles(logTxt, "*.log");

            fileNames.OrderBy(x => x).ToList().ForEach(x =>
            {
                this.lb_Files.Items.Add(Path.GetFileName(x));
            });
        }

        private async void lb_Files_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cb_Date.SelectedItem == null)
            {
                UIMessageTip.ShowError("请选择日期！");
                return;
            }
            if (this.cb_LogLev.SelectedItem == null)
            {
                UIMessageTip.ShowError("请选择日志等级！");
                return;
            }
            if (this.lb_Files.SelectedItem == null)
            {
                UIMessageTip.ShowError("请选择展示日志！");
                return;
            }
            try
            {
                //选择log 文件后，显示日志内容
                string logTxt = Path.Combine(Application.StartupPath, "Logs",
                    this.cb_Date.SelectedItem.ToString(), this.cb_LogLev.SelectedItem.ToString(), this.lb_Files.SelectedItem.ToString());

                string content = string.Empty;
                this.txt_ShowLog.Text = "";

                using (StreamReader sr = new StreamReader(logTxt))
                {
                    content = await sr.ReadToEndAsync();
                }
                this.txt_ShowLog.Text = content;
            }
            catch (Exception ex)
            {

                UIMessageTip.ShowError("日志txt显示错误");
                LogExtension.ShowMessage(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error);
            }
        }

        private void btn_OpenDire_Click(object sender, EventArgs e)
        {
            string logDirPath = Path.Combine(Application.StartupPath, "Logs");
            ProcessStartInfo processStartInfo = new ProcessStartInfo()
            {
                FileName = logDirPath,
                UseShellExecute = true
            };
            Process process = new Process()
            {
                StartInfo = processStartInfo
            };
            process.Start();
        }

        private void btn_ShowToDgv_Click(object sender, EventArgs e)
        {
            if (this.txt_ShowLog.Text.Length == 0)
            {
                UIMessageTip.ShowWarning("请选择日志文件");
                return;
            }
            //按照回车分割成行，并且删除空格
            string[] lines = this.txt_ShowLog.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

            DataTable dt = new DataTable();
            dt.Columns.Add("时间", typeof(string));
            dt.Columns.Add("日志等级", typeof(string));
            dt.Columns.Add("日志来源", typeof(string));
            dt.Columns.Add("日志内容", typeof(string));

            lines.ToList().ForEach(line =>
            {
                string[] items = line.Split(new string[] { "|" }, StringSplitOptions.None);
                if (items.Length == 4)
                {
                    DataRow dr = dt.NewRow();
                    dr["时间"] = items[0];
                    dr["日志等级"] = items[1];
                    dr["日志来源"] = items[2];
                    dr["日志内容"] = items[3];
                    dt.Rows.Add(dr);
                }
            });
            this.dgv_ShowLog.DataSource = dt;
        }

        private void btn_ShowToTXT_Click(object sender, EventArgs e)
        {
            if (this.txt_ShowLog.Text == string.Empty)
            {
                UIMessageTip.ShowWarning("请选择日志文件");
                return;
            }
            SaveFileDialog sdf = new SaveFileDialog();
            sdf.Filter = "txt文件|*.txt";
            sdf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

            if (sdf.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (StreamWriter sw = new StreamWriter(sdf.FileName))
                    {
                        sw.Write(this.txt_ShowLog.Text);
                    }
                    UIMessageTip.ShowOk("日志文件导出成功！");
                    LogExtension.ShowMessage("日志文件导出成功！", Microsoft.Extensions.Logging.LogLevel.Information);

                    //打开文件
                    ProcessStartInfo processStartInfo = new ProcessStartInfo()
                    {
                        FileName = sdf.FileName,
                        UseShellExecute = true
                    };
                    Process process = new Process()
                    {
                        StartInfo = processStartInfo
                    };
                    process.Start();
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowError(ex.Message);
                    LogExtension.ShowMessage(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error);
                }
            }
        }

        private async void btn_ExportExcel_Click(object sender, EventArgs e)
        {
            if (this.dgv_ShowLog.DataSource == null)
            {
                UIMessageTip.ShowWarning("请选择日志文件");
                return;
            }
            SaveFileDialog sdf = new SaveFileDialog();
            sdf.Filter = "Excel文件|*.xlsx";
            sdf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            
            if (sdf.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    DataTable dt = this.dgv_ShowLog.DataSource as DataTable;

                    await MiniExcel.SaveAsAsync(sdf.FileName, dt);
                    UIMessageTip.ShowOk("日志文件导出成功！");
                    LogExtension.ShowMessage("日志文件导出成功！", Microsoft.Extensions.Logging.LogLevel.Information);

                    //打开文件
                    ProcessStartInfo processStartInfo = new ProcessStartInfo()
                    {
                        FileName = sdf.FileName,
                        UseShellExecute = true
                    };
                    Process process = new Process()
                    {
                        StartInfo = processStartInfo
                    };
                    process.Start();
                }
                catch (Exception ex)
                {
                    UIMessageTip.ShowError(ex.Message);
                    LogExtension.ShowMessage(ex.Message, Microsoft.Extensions.Logging.LogLevel.Error);
                }
            }
        }
        #region 窗体切换卡顿
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams paras = base.CreateParams;
                paras.ExStyle |= 0x02000000;
                return paras;
            }
        }
        #endregion
    }
}
